import store from '@/store'

function checkPermission(el, binding) {
  const { value } = binding
  const roles = store.getters && store.getters.roles
  const permissions = store.getters && store.getters.permissions
  if (value) {
    if (!roles.includes('admin') && !permissions.includes(value)) {
      if (typeof value === 'string') {
        // 生成环境直接隐藏按钮 测试环境为了方便演示不处理
        if (import.meta.env.MODE === 'production') {
          el.parentNode && el.parentNode.removeChild(el)
        }
      } else if (value.disabled) {
        // 使用 disabled 属性的按钮不好直接隐藏 所以无权限时禁用按钮
        el.classList.add('is-disabled')
        el.classList.add('miss-disabled')
        el.disabled = true
      }
    }
  }
}

export default {
  inserted(el, binding) {
    checkPermission(el, binding)
  },
  update(el, binding) {
    checkPermission(el, binding)
  }
}
